import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.RichSourceFunction;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;

public class UDAF {


    public static void main(String[] args) throws Exception {


        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);

        DataStream<Row> ds3 = env.addSource(new RichSourceFunction<Row>() {
            @Override
            public void run(SourceContext<Row> ctx) throws Exception {
                Row row1 = new Row(2);
                row1.setField(0, "a");
                row1.setField(1, 1L);

                Row row2 = new Row(2);
                row2.setField(0, "a");
                row2.setField(1, 2L);

                Row row3 = new Row(2);
                row3.setField(0, "b");
                row3.setField(1, 100L);

                ctx.collect(row1);
                ctx.collect(row2);
                ctx.collect(row3);

            }

            @Override
            public void cancel() {

            }
        }).returns(Types.ROW(Types.STRING, Types.LONG));

        tEnv.createTemporaryView("t3", ds3, "name,cnt");

        tEnv.registerFunction("test3", new TestAggregateFunction());

        Table table3 = tEnv.sqlQuery("select name,test3(cnt) as mySum from t3 group by name");

        DataStream<Tuple2<Boolean, Row>> res3 = tEnv.toRetractStream(table3, Row.class);

        //        res3.print().name("Aggregate Functions Print").setParallelism(1);


        res3.print();

        env.execute();

    }


}